

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import com.facebook.api.*;
import com.facebook.api.schema.*;

/**
 * Servlet implementation class for Servlet: Login
 *
 */
 public class Login extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;
   
    /* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public Login() {
		super();
	}   	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//Recupere les clés dans le servlet config
		String apiKey = getServletConfig().getInitParameter("API_KEY");
		String secretKey = getServletConfig().getInitParameter("SECRET_KEY");
		
		FacebookRestClient fbrclient = null;
		
		HttpSession session = request.getSession();
		String sessionKey = (String) session.getAttribute("facebookSession");
		String token = request.getParameter("auth_token");
		
		if(sessionKey != null && sessionKey.length() > 0){
			fbrclient = new FacebookRestClient(apiKey,secretKey,sessionKey);
		}else if( token != null ){
			//creation d'un session facebook
			fbrclient = new FacebookRestClient(apiKey,secretKey);
			fbrclient.setIsDesktop(false);
			
			try {
				sessionKey = fbrclient.auth_getSession(token);
				session.setAttribute("facebookSession", sessionKey);
			} catch (FacebookException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}else{
			//redirection vers la page de login
			response.sendRedirect("http://www.facebook.com/login.php?api_key="+ apiKey + "&v=1.0");
			return;
		}
		
		getUserInfos(request, fbrclient);
		
		request.getRequestDispatcher("infoUser.jsp").forward(request, response);
		//response.getWriter().println("Hello Polytech");
		
	}  	
	
	private void getUserInfos(HttpServletRequest request,
			FacebookRestClient fbrclient) {
		// TODO Auto-generated method stub
		try {
			long myID = fbrclient.users_getLoggedInUser();
			
			EnumSet<ProfileField> fields = EnumSet.of(
					com.facebook.api.ProfileField.NAME,
					com.facebook.api.ProfileField.PIC);
			
			ArrayList<Long> users = new ArrayList<Long>();
			users.add(myID);
			//add my friends ids
			
			
			fbrclient.friends_get();
			FriendsGetResponse friendsResp = (FriendsGetResponse)fbrclient.getResponsePOJO();
			List<Long> friends = friendsResp.getUid();
			int nbFriends = friends.size();
			Iterator<Long> it = friends.iterator();
			while(it.hasNext()){
				users.add(it.next());
			}
			
			fbrclient.groups_get(null,null);
			GroupsGetResponse groupsResp = (GroupsGetResponse)fbrclient.getResponsePOJO();
			List<Group> groups = groupsResp.getGroup();
			int nbGroups = groups.size();
			Iterator<Group> it2 = groups.iterator();
			while(it2.hasNext()){
				Group g = it2.next();
				Document d = fbrclient.groups_getMembers(g.getGid());
				
				NodeList list = d.getElementsByTagName("uid");
			
				for (int i = 0; i < list.getLength(); ++i){
					users.add(Long.valueOf(list.item(i).getTextContent()));
				}
			}
			System.out.println(users);
			
			//recuperation des informations
			fbrclient.users_getInfo(users, fields);
			UsersGetInfoResponse usersInfo = (UsersGetInfoResponse) fbrclient.getResponsePOJO();
			
			
			request.setAttribute("users", usersInfo.getUser());
			
			request.setAttribute("nbGroups", nbGroups);
			request.setAttribute("nbFriends", nbFriends);
		} catch (FacebookException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}   	  	    
}